import smb2 from "../dist";
import fs from "fs";
import {
  createHash,
} from 'crypto';

const length64 = 64*1024

export default async (host: string, domain: string, username: string, password: string, share: string) => {
  let client
  try {
    client = new smb2.Client(host);
    const session = await client.authenticate({
      domain,
      username,
      password
    });
    const tree = await session.connectTree(share);

    // const entries = await tree.readDirectory("/");
    // console.log(entries);

    // const unwatch = await tree.watch(response => {
    //   console.log("changed", response.data);
    // });
    // await tree.createDirectory('test')
    // await tree.createDirectory('test/1')
    // await tree.createDirectory('test/1/2')
    const filesize = 3266004992
    console.log('start')
    const isEx = await tree.exists('cn_windows_7_professional_with_sp1_vl_build_x64_dvd_u_677816.iso')
    console.log(isEx, 1)
    if(isEx) await tree.removeFile('cn_windows_7_professional_with_sp1_vl_build_x64_dvd_u_677816.iso')
    console.log(2)
    const file = await tree.createEmptyFile(['cn_windows_7_professional_with_sp1_vl_build_x64_dvd_u_677816.iso'])
    console.log(3)
    const readStream = fs.createReadStream('/home/caocong/下载/cn_windows_7_professional_with_sp1_vl_build_x64_dvd_u_677816.iso', {highWaterMark: 4 * 1024 * 1024});
    let point = 0
    readStream.on('data', (data) => {
      console.log('readStream data')
      const l = data.length
      readStream.pause()
      const promiseList = []
      if(l>length64){
        const count = Math.ceil(l / length64)
        const oriPoint = point
        for(let i = 0;i < count;i++){
          const nextPoint = i < count -1 ? length64 : oriPoint + l
          promiseList.push(file.writeBuffer(point, data.slice(point - oriPoint, nextPoint - oriPoint)))
          point = nextPoint
        }
        // console.log(point - oriPoint, l, count)
      }else{
        promiseList.push(file.writeBuffer(point, data))
        point += l
      }
      Promise.all(promiseList).then(() => {
        // point += l
        console.log(point, l)
        if(point === filesize){
          client.close()
          readStream.destroy()
        }else{
          readStream.resume()
        }
      }).catch(err=>console.error(err))
    })
    // const filename = 'LdapBrowser-6.10.x-win-x86-Setup.msi'
    // const readStream = await tree.readFileStream(filename)
    // const writeStream = fs.createWriteStream("/home/caocong/文档/"+filename)
    // readStream.pipe(writeStream)
    // readStream.on('data', data =>{
    //   console.log('readStream data', data.length)
    // })
    // writeStream.on('unpipe', ()=>{
    //   console.log('writeStream unpipe')
    // })
    // readStream.on('close', () =>{
    //   console.log('readStream close')
    // })
    // readStream.on('pipe', ()=>{
    //   console.log('readStream pipe')
    // })
    // readStream.on('unpipe', ()=>{
    //   console.log('readStream unpipe')
    // })
    // readStream.on('close', ()=>{
    //   console.log('readStream close')
    // })
    // writeStream.on('pipe', ()=>{
    //   console.log('writeStream pipe')
    // })
    // writeStream.on('close', ()=>{
    //   console.log('writeStream close')
    // })


    // const readStream = await tree.readFileStream('personal/user155/其他/apache-tomcat-9.0.44.tar.gz')
    // const hash = createHash('sha256');
    // readStream.on('error', err =>{});
    // readStream.on('data', chunk => {
    //   hash.update(chunk)
    //   console.log('data', chunk.length)
    // });
    // readStream.on('end', () => {
    //   const h = hash.digest('hex')
    //   console.log('end', h)
    // });
    // const hash = createHash('sha256');
    // readStream.on('finish', ()=>{
    //   console.log('finish', readStream.read())
    // }).on('unpipe', ()=>{
    //   console.log('unpipe', readStream.read())
    // });
    // const a = readStream.pipe(hash).setEncoding('hex').pipe(process.stdout)

    // const writeStream =  fs.createWriteStream('/home/caocong/文档/gdata.zip')
    // // writeStream.pipe(readStream)
    // readStream.pipe(writeStream)
    // let point = 0
    // readStream.on('data', (data) =>{
    //   point += data.length
    //   console.log('readStream', data.length, point)
    // })
    // readStream.on('close', () =>{
    //   console.log('readStream close')
    // })
    // writeStream.on('unpipe', d =>{
    //   console.log('writeStream unpipe', d)
    // })
    

    // if (!await tree.exists(directoryName)) await tree.createDirectory(directoryName);
    // console.log("directory content", await tree.readDirectory(directoryName));
    //
    // if (!await tree.exists(`${directoryName}/${filename}`)) await tree.createFile(`${directoryName}/${filename}`, "1234");
    // console.log("file content", (await tree.readFile(`${directoryName}/${filename}`)).toString());
    // setTimeout(async () => {
    //   try {
    //     await tree.removeFile(`${directoryName}/${filename}`);
    //   } catch (err) {
    //     console.error("failed remove file", err);
    //   }
    // }, 3 * 1000);
    //
    // setTimeout(async () => {
    //   try {
    //     await tree.removeDirectory(directoryName);
    //   } catch (err) {
    //     console.error("failed remove dir", err);
    //   }
    // }, 5 * 1000);
    //
    // setTimeout(async () => {
    //   await unwatch();
    //   console.log("no longer watching");
    //
    //   await client.close();
    //   console.log("client closed");
    // }, 8 * 1000);
  } catch (err) {
    if(client){
      client.close()
    }
    console.error("error", err);
  }
};